//
//  PhotoBrowserCollectionViewCell.swift
//  ImageBrowse
//
//  Created by zs on 16/6/19.
//  Copyright © 2016年 zs. All rights reserved.
//

import UIKit
import SDWebImage

class PhotoBrowserCollectionViewCell: UICollectionViewCell {
  // MARK:- 定义属性
    var shop : Shop? {
        didSet {
           //1.获取Shop中对应图片的URLString
            guard let urlString = shop?.q_pic_url else {
            
              return
            }
            
            //2.根据url获取到小图片
            var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
            if smallImage == nil {
                smallImage = UIImage(named: "empty_picture")
            }
            
            //3.计算小图方法之后的尺寸
            imageView.frame = calculateFrame(smallImage)
            
            //4.设置大图
            guard let bigImageUrlString = shop?.d_pic_url else {
              imageView.image = smallImage
                return
            }
            
            let bigImageURL = NSURL(string: bigImageUrlString)
            imageView.sd_setImageWithURL(bigImageURL, placeholderImage: smallImage)
        }
    }
    
     lazy var imageView : UIImageView = UIImageView()
    
  override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}




extension PhotoBrowserCollectionViewCell {
  private func setUpUI() {
      
       contentView.addSubview(imageView)
    }
}

extension PhotoBrowserCollectionViewCell {
  
    func calculateFrame(image : UIImage) -> CGRect{
      //获取图片的高度
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        let x : CGFloat = 0
        let y = (UIScreen.mainScreen().bounds.height - h) * 0.5
        return CGRect(x: x, y: y, width: w, height: h)
    }

}